package com.gupao.javavip.netty.push.protocol;

import com.gupao.javavip.netty.push.client.connection.RetryConnector;
import com.gupao.javavip.netty.push.client.processor.handler.ReconnectHandler;
import com.gupao.javavip.netty.push.server.processor.handler.ServerIdleStateTrigger;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

public abstract class AbstractPushChannelInitializer extends ChannelInitializer<SocketChannel> {
    private boolean server;
    private boolean retry;//断开重连
    private RetryConnector connector;

    public AbstractPushChannelInitializer() {
        this(false);
    }

    public AbstractPushChannelInitializer(boolean server) {
        this(server, false, null);
    }

    public AbstractPushChannelInitializer(boolean server, boolean retry, RetryConnector connector) {
        this.server = server;
        this.retry = retry;
        this.connector = connector;
    }

    /**
     * Channel初始化处理
     * 对消息尾的处理
     *
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //Inbound
        if (server) {
            ch.pipeline().addLast("idle-state-handler", new IdleStateHandler(30, 0, 0));
            ch.pipeline().addLast("idle-state-trigger", new ServerIdleStateTrigger());
        }

        if (!server && retry) {
            ch.pipeline().addLast("reconnect-handler", new ReconnectHandler(connector));
        }

        ch.pipeline().addLast("delimiter-decoder", new DelimiterBasedFrameDecoder(2048, MessageDelimiterEncoder.DELIMITER_BYTE_BUF));

        //Outbound
        ch.pipeline().addLast("delimiter-encoder", new MessageDelimiterEncoder());

        doInitChannel(ch);
    }

    /**
     * Channel初始化处理
     *
     * @param ch
     */
    protected abstract void doInitChannel(SocketChannel ch);
}
